package com.ddstation.verifycode.controller;

import com.ddstation.verifycode.entity.VerifycodeEntity;
import com.ddstation.verifycode.property.VerifyCodeProperties;
import com.ddstation.verifycode.service.VerifycodeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.inject.Inject;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

//@Controller
public class VerifycodeController {
	
	@RequestMapping(value="verifycode.do/get")
	public @ResponseBody Map<String, Object> getVerfycodeEvent(
			@RequestParam String phone) {
		
		Map<String, Object> ret = new HashMap<String, Object>();
		ret.put("errcode", 0);
		ret.put("v", verifycodeService.create(phone, VerifyCodeProperties.VERIFY_CODE_EXPIRES_SHORTMESSAGE * 60));
		return ret;
	}
	
	@RequestMapping(value="verifycode.do/validate")
	public @ResponseBody Map<String, Object> validateVerfycodeEvent(
			@RequestParam(required=false) String phone,
			@RequestParam(required=false) String code,
			@RequestParam(required=false) Long timelimit,
			@RequestParam(required=false) String datasign
			) {
		Map<String, Object> ret = new HashMap<String, Object>();
		if (StringUtils.isBlank(phone) || 
			StringUtils.isBlank(code) || 
			timelimit == null || 
			StringUtils.isBlank(datasign)) {
			ret.put("errcode", -1); // 验证码不正确
		} else {
			if (timelimit < new Date().getTime()) {
				ret.put("errcode", -2); // 验证码失效
			} else {
				VerifycodeEntity v = new VerifycodeEntity();
				v.setCode(code);
				v.setPhone(phone);
				v.setTimelimit(timelimit);
				v.setDatasign(datasign);
				if (verifycodeService.validate(v)) {
					ret.put("errcode", 0);
				} else {
					ret.put("errcode", -1); // 验证码不正确
				}
			}
		}
		return ret;
	}
	
	private @Inject VerifycodeService verifycodeService = null;
}
